import React from 'react';
import { Table, Modal, message, Button, Space, Tag, Tooltip, Typography } from 'antd';
import { 
    EyeOutlined, 
    EditOutlined, 
    DeleteOutlined, 
    ScanOutlined, 
    FileTextOutlined, 
    ClearOutlined,
    LinkOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { deleteUnit, manualTriggerScan } from '../../services/unit';

const { Link } = Typography;

const UnitTable: React.FC<{
    data: any[];
    pagination: any;
    loading: boolean;
    onChange: (pagination: any) => void;
    onDelete?: () => void;
}> = ({ data, pagination, loading, onChange, onDelete }) => {
    const navigate = useNavigate();

    const columns = [
        {
            title: <span style={{ fontWeight: '600', color: '#262626' }}>单元ID</span>,
            dataIndex: 'unitId',
            key: 'unitId',
            width: 180,
            render: (text: string, record: any) => (
                <Button
                    type="link"
                    onClick={() => navigate(`/unit/${record.unitId}`)}
                    style={{ 
                        padding: 0, 
                        height: 'auto', 
                        fontWeight: '500',
                        color: '#1890ff'
                    }}
                >
                    {text}
                </Button>
            ),
        },
        { 
            title: <span style={{ fontWeight: '600', color: '#262626' }}>单元类型</span>,
            dataIndex: 'unitType', 
            key: 'unitType',
            width: 120,
            render: (text: string) => {
                if (!text) return <span style={{ color: '#d9d9d9' }}>-</span>;
                
                // 处理组合的单元类型字符串，例如："后端服务/HT-标准微服务/HT-DUBBO-JAVA"
                const parts = text.split('/');
                if (parts.length === 3) {
                    // 显示最后一级类型，鼠标悬停显示完整信息
                    return (
                        <Tooltip title={`${parts[0]} / ${parts[1]} / ${parts[2]}`}>
                            <Tag color="blue" style={{ borderRadius: '4px' }}>
                                {parts[2]}
                            </Tag>
                        </Tooltip>
                    );
                } else {
                    // 如果不是三级格式，直接显示
                    return (
                        <Tag color="blue" style={{ borderRadius: '4px' }}>
                            {text}
                        </Tag>
                    );
                }
            }
        },
        { 
            title: <span style={{ fontWeight: '600', color: '#262626' }}>归属应用</span>,
            dataIndex: 'appId', 
            key: 'appId',
            width: 140,
            render: (text: string) => (
                <span style={{ color: '#595959', fontWeight: '500' }}>
                    {text || '-'}
                </span>
            )
        },
        { 
            title: <span style={{ fontWeight: '600', color: '#262626' }}>开发团队</span>,
            dataIndex: 'ownTeam', 
            key: 'ownTeam',
            width: 140,
            render: (text: string) => (
                <span style={{ color: '#595959' }}>
                    {text || '-'}
                </span>
            )
        },
        { 
            title: <span style={{ fontWeight: '600', color: '#262626' }}>Git仓库</span>,
            dataIndex: 'gitRepoUrl', 
            key: 'gitRepoUrl',
            width: 200,
            ellipsis: true,
            render: (text: string) => text ? (
                <Tooltip title={text}>
                    <Link 
                        href={text} 
                        target="_blank" 
                        rel="noopener noreferrer"
                        style={{ color: '#1890ff' }}
                    >
                        <LinkOutlined style={{ marginRight: '4px' }} />
                        {text.length > 30 ? `${text.substring(0, 30)}...` : text}
                    </Link>
                </Tooltip>
            ) : (
                <span style={{ color: '#d9d9d9' }}>未配置</span>
            )
        },
        {
            title: <span style={{ fontWeight: '600', color: '#262626' }}>当前分支</span>,
            dataIndex: 'currentBranch',
            key: 'currentBranch',
            width: 140,
            render: (text: string) => text ? (
                <Tag color="green" style={{ borderRadius: '4px' }}>
                    {text}
                </Tag>
            ) : (
                <span style={{ color: '#d9d9d9' }}>未设置</span>
            )
        },
        {
            title: <span style={{ fontWeight: '600', color: '#262626' }}>操作</span>,
            key: 'action',
            width: 260,
            fixed: 'right' as const,
            render: (_: any, record: any) => (
                <Space size="middle">
                    <Tooltip title="查看详情">
                        <Button
                            type="text"
                            size="small"
                            icon={<EyeOutlined />}
                            onClick={() => navigate(`/unit/${record.unitId}`)}
                            style={{ color: '#1890ff' }}
                        />
                    </Tooltip>
                    
                    <Tooltip title="扫描记录">
                        <Button
                            type="text"
                            size="small"
                            icon={<FileTextOutlined />}
                            onClick={() => navigate(`/scan-records/${record.unitId}`)}
                            style={{ color: '#52c41a' }}
                        />
                    </Tooltip>
                    
                    <Tooltip title="清理记录">
                        <Button
                            type="text"
                            size="small"
                            icon={<ClearOutlined />}
                            onClick={() => navigate(`/clean-records/${record.unitId}`)}
                            style={{ color: '#faad14' }}
                        />
                    </Tooltip>
                    
                    <Tooltip title="触发扫描">
                        <Button
                            type="text"
                            size="small"
                            icon={<ScanOutlined />}
                            onClick={async () => {
                                try {
                                    await manualTriggerScan(record.unitId);
                                    message.success('扫描任务已触发');
                                    onDelete && onDelete();
                                } catch (e: any) {
                                    message.error(e?.response?.data?.msg || '触发扫描失败');
                                }
                            }}
                            style={{ color: '#722ed1' }}
                        />
                    </Tooltip>
                    
                    <Tooltip title="编辑">
                        <Button
                            type="text"
                            size="small"
                            icon={<EditOutlined />}
                            onClick={() => navigate(`/unit/${record.unitId}/edit`)}
                            style={{ color: '#1890ff' }}
                        />
                    </Tooltip>
                    
                    <Tooltip title="删除">
                        <Button
                            type="text"
                            size="small"
                            icon={<DeleteOutlined />}
                            onClick={() => {
                                Modal.confirm({
                                    title: '确认删除',
                                    content: (
                                        <div>
                                            <p>确定要删除单元 <strong>{record.unitId}</strong> 吗？</p>
                                            <p style={{ color: '#ff4d4f', fontSize: '12px' }}>
                                                此操作不可逆，请谨慎操作。
                                            </p>
                                        </div>
                                    ),
                                    okText: '删除',
                                    okType: 'danger',
                                    cancelText: '取消',
                                    okButtonProps: { 
                                        style: { borderRadius: '6px' }
                                    },
                                    cancelButtonProps: { 
                                        style: { borderRadius: '6px' }
                                    },
                                    onOk: async () => {
                                        try {
                                            await deleteUnit(record.unitId);
                                            message.success('删除成功');
                                            onDelete && onDelete();
                                        } catch (e: any) {
                                            message.error(e?.response?.data?.msg || '删除失败');
                                        }
                                    },
                                });
                            }}
                            style={{ color: '#ff4d4f' }}
                            danger
                        />
                    </Tooltip>
                </Space>
            ),
        },
    ];

    return (
        <Table
            rowKey="unitId"
            columns={columns}
            dataSource={data}
            loading={loading}
            scroll={{ x: 1200 }}
            pagination={{
                current: pagination.current,
                pageSize: pagination.pageSize,
                total: pagination.total,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) => (
                    <span style={{ color: '#595959' }}>
                        显示第 {range[0]}-{range[1]} 条，共 {total} 条记录
                    </span>
                ),
                pageSizeOptions: ['10', '20', '50', '100'],
                style: { marginTop: '16px' }
            }}
            onChange={onChange}
            size="middle"
            style={{ 
                background: '#fff',
                borderRadius: '8px'
            }}
            rowClassName={() => 'hover-row'}
        />
    );
};

export default UnitTable; 